import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Input, Button, Checkbox, Table, TreeSelect, message, Space, Select, Row, Col } from 'antd'
import style from './Index.module.less'
const { Option } = Select
function getColumns () {
  const list = [
    {
      title: '姓名',
      dataIndex: 'name',
      width: 80
    },
    {
      title: '名册序号',
      dataIndex: 'serialno',
      key: 'serialno',
      align: 'center',
      width: 80
    },
    {
      title: '单位',
      dataIndex: 'structure',
      width: 120
    },
    {
      title: '职业分类',
      dataIndex: 'occupation',
      width: 100
    },
    {
      title: '擅长专业',
      dataIndex: 'special',
      width: '200px'
    },
    {
      title: '金融专业',
      dataIndex: 'causeaction_class',
      width: '100px'
    },
    {
      title: '在办',
      dataIndex: 'caseing',
      width: '60px',
      align: 'center'
    },
    {
      title: '今年总办',
      dataIndex: 'caseon',
      sorter: true,
      width: '118px',
      align: 'center'
    },
    {
      title: '首',
      dataIndex: 'caseon1',
      sorter: true,
      width: '60px',
      align: 'center'
    },
    {
      title: '独',
      dataIndex: 'caseon2',
      sorter: true,
      width: '60px',
      align: 'center'
    },
    {
      title: '边',
      dataIndex: 'caseon3',
      sorter: true,
      width: '60px',
      align: 'center'
    }
  ]
  if (this.state.actions) {
    list[1].width = '200px'
    list[3].width = '250px'
    list.splice(5, 0, {
      title: '同案由',
      dataIndex: 'cause_action_count',
      sorter: true,
      width: '108px',
      align: 'center'
    })
  }
  return list
}

class ArbitratorList extends Component {
  state = {
    areaOptions: ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '佳木斯市', '大庆市', '鸡西市', '双鸭山市', '鹤岗市', '七台河市', '伊春市', '黑河市', '绥化市', '大兴安岭地区', '外省', '外籍'],
    detailAreaOptions: [],
    areaMap: {},
    occupationMap: {},
    detailAreaVisible: false,
    areaIndeterminate: false,
    areaCheckAll: true,
    areaCheckedList: [],
    typeOptions: [],
    typeIndeterminate: false,
    typeCheckAll: true,
    typeCheckedList: [],
    list: [],
    selectedRowKeys: [],
    actions: undefined,
    name: '',
    orderField: '',
    order: '',
    pagination: {
      current: 1,
      pageSize: 5,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 位`,
      size: 'small'
    },
    loading: false,
    majors: [],
    professional: undefined,
    retire: '全部',
    onlyNew: '全部',
    causeActionTree: [],
    causeactionClassList: [],
    causeactionClass: undefined
  }

  // 获取案由树
  getCauseActionTree () {
    return this.$get('/api/common/cause_action')
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({ causeActionTree: res.data })
      })
  }

  // 获取专业小项
  getCauseactionClassList () {
    return this.$get('/api/xapc/dictionary/getTreeByType', {
      type: '案件分类'
    }).then(res => {
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      const arr = res.data.filter(li => li.value === '金融案件')
      const l = arr[0].children.map(li => li.value)
      this.setState({
        causeactionClassList: l
      })
    })
  }

  // 获取所在区域
  getAreaMap () {
    return this.$get('/api/xapc/arbitrator/area')
      .then(res => {
        if (res.status === 1) {
          this.formatArea(res.data)
        } else {
          message.warning(res.message)
        }
      })
  }

  // 获取专业
  getDictionary () {
    this.$get('/api/xapc/dictionary', {
      types: '专业'
    }).then(res => {
      if (res.status === 1) {
        this.setState({
          majors: res.data[0].list.map(li => li.value)
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 格式化所在区域
  formatArea (data) {
    const keys = Object.keys(data)
    let result = []
    keys.forEach(key => {
      result = [...result, ...data[key]]
    })
    this.setState({
      detailAreaOptions: result,
      areaCheckedList: this.state.areaOptions.slice(),
      areaMap: data
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 从字典中获取仲裁员类型
  getTypeFromDictionary () {
    return this.$get('/api/xapc/dictionary', {
      types: '仲裁员职业分类'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        const typeOptions = (dictionaries['仲裁员职业分类'] || []).map(li => li.title)
        this.setState({
          occupationMap: dictionaries['仲裁员职业分类'],
          typeOptions,
          typeCheckedList: typeOptions.slice()
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 获取基础数据
  getBaseData () {
    Promise.all([this.getCauseActionTree(), this.getCauseactionClassList(), this.getAreaMap(), this.getTypeFromDictionary()])
      .then(() => {
        this.getList()
      })
  }

  // 获取查询参数
  getParams (form) {
    const { pagination, status, typeCheckedList, areaMap, name, actions, retire, professional, onlyNew, orderField, order, causeactionClass } = this.state
    let areaCheckedList = this.state.areaCheckedList.slice()
    const { current, pageSize } = pagination
    const condition = [{ k: 'professional_class', o: '=', v: '金融' }]
    if (areaCheckedList.length) {
      const otherIndex = areaCheckedList.indexOf('外省')
      if (otherIndex !== -1) {
        areaCheckedList.splice(otherIndex, 1)
        areaCheckedList = [...areaCheckedList, ...(areaMap['外省'] || [])]
      }
      const foreignIndex = areaCheckedList.indexOf('外籍')
      if (foreignIndex !== -1) {
        areaCheckedList.splice(foreignIndex, 1)
        areaCheckedList = [...areaCheckedList, ...(areaMap['外籍'] || [])]
      }
      condition.push({ k: 'area', o: 'in', v: areaCheckedList.join(',') })
    }
    if (typeCheckedList.length) {
      condition.push({ k: 'occupation', o: 'in', v: typeCheckedList.join(',') })
    }
    if (name) {
      condition.push({ k: 'name', o: 'like', v: `%${name}%` })
    }
    if (actions) {
      condition.push({ k: 'cause_action', o: 'like', v: `%${actions}%` })
    }
    if (retire !== '全部') {
      condition.push({ k: 'retire', o: '=', v: retire })
    }
    if (onlyNew === '2021年3月1日') {
      condition.push({ k: 'appoint_datetime ', o: '=', v: '1614528000' })
    } else if (onlyNew === '2021年6月1日') {
      condition.push({ k: 'appoint_datetime ', o: '=', v: '1622476800' })
    } if (onlyNew === '2021年3月之前') {
      condition.push({ k: 'appoint_datetime ', o: 'null' })
    }
    if (professional) {
      condition.push({ k: 'professional', o: 'like', v: `%${professional}%` })
    }
    if (causeactionClass) {
      condition.push({ k: 'causeaction_class', o: 'like', v: `%${causeactionClass}%` })
    }
    this.setState({ loading: true })
    const data = {
      caseid: this.props.caseDetail.id,
      current,
      page_size: pageSize,
      status,
      ...form,
      condition: JSON.stringify(condition)
    }
    if (orderField && order) {
      data.order = order === 'ascend' ? 'asc' : 'desc'
      data.order_field = orderField
    }
    if (!actions && orderField === 'cause_action_count') {
      delete data.order
      delete data.order_field
    }
    return data
  }

  // 获取仲裁员列表
  getList (form = {}) {
    const { pagination } = this.state
    const { current, pageSize } = pagination
    this.$get('/api/xapc/arbitratorcase', this.getParams(form)).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        }, () => {
          this.initSelected()
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 初始化选中项
  initSelected () {
    const list = this.state.list
    const { value } = this.props
    if (!value) {
      this.setState({
        selectedRowKeys: []
      })
    }
    for (let i = 0; i < list.length; i++) {
      if (list[i].id === value) {
        this.setState({
          selectedRowKeys: [i]
        })
        break
      }
    }
  }

  // 改变多选项
  changeCheckbox (type, list) {
    const options = this.state[type + 'Options']
    this.setState({
      [type + 'CheckedList']: list,
      [type + 'Indeterminate']: !!list.length && list.length < options.length,
      [type + 'CheckAll']: list.length === options.length
    })
  }

  // 点击全选按钮
  changeAll (type, e) {
    this.setState({
      [type + 'CheckedList']: e.target.checked ? this.state[type + 'Options'] : [],
      [type + 'Indeterminate']: false,
      [type + 'CheckAll']: e.target.checked
    })
  }

  // 改变选中项
  onSelectChange = selectedRowKeys => {
    const { current, pageSize } = this.state.pagination
    const i = selectedRowKeys[0] - (current - 1) * pageSize
    const o = this.state.list[i]
    if (this.props.disabledIdList.indexOf(o.id) !== -1) {
      return false
    }
    this.setState({ selectedRowKeys }, () => {
      this.props.onChange({ arbitrator: o.name, arbitratorid: o.id })
    })
  }

  // 全选区域
  changeAllArea (e) {
    const options = this.state.detailAreaVisible ? this.state.detailAreaOptions : this.state.areaOptions
    this.setState({
      areaCheckedList: e.target.checked ? options : [],
      areaIndeterminate: false,
      areaCheckAll: e.target.checked
    })
  }

  // 改变区域多选项
  changeAreaCheckbox (list) {
    const options = this.state.detailAreaVisible ? this.state.detailAreaOptions : this.state.areaOptions
    this.setState({
      areaCheckedList: list,
      areaIndeterminate: !!list.length && list.length < options.length,
      areaCheckAll: list.length === options.length
    })
  }

  // 展开详细区域
  showDetailArea () {
    this.setState({
      detailAreaVisible: true
    }, () => {
      if (this.state.areaCheckAll) {
        this.changeAreaCheckbox(this.state.detailAreaOptions)
      } else {
        let list = []
        const checkedList = this.state.areaCheckedList
        const areaMap = this.state.areaMap
        const areaList = ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '佳木斯市', '大庆市', '鸡西市', '双鸭山市', '鹤岗市', '七台河市', '伊春市', '黑河市', '绥化市', '大兴安岭地区']
        areaList.forEach(li => {
          if (checkedList.indexOf(li) !== -1) {
            list.push(li)
          }
        })
        if (checkedList.indexOf('外省') !== -1) {
          list = [...list, ...(areaMap['外省'] || [])]
        }
        if (checkedList.indexOf('外籍') !== -1) {
          list = [...list, ...(areaMap['外籍'] || [])]
        }
        this.changeAreaCheckbox(list)
      }
    })
  }

  // 隐藏详细区域
  hideDetailArea () {
    this.setState({
      detailAreaVisible: false
    }, () => {
      if (this.state.areaCheckAll) {
        this.changeAreaCheckbox(this.state.areaOptions)
      } else {
        const list = []
        const checkedList = this.state.areaCheckedList
        const areaMap = this.state.areaMap
        const hasOther = (areaMap['外省'] || []).every(a => checkedList.indexOf(a) !== -1)
        const hasForeign = (areaMap['外籍' || []]).every(a => checkedList.indexOf(a) !== -1)
        const areaList = ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '佳木斯市', '大庆市', '鸡西市', '双鸭山市', '鹤岗市', '七台河市', '伊春市', '黑河市', '绥化市', '大兴安岭地区']
        areaList.forEach(li => {
          if (checkedList.indexOf(li) !== -1) {
            list.push(li)
          }
        })
        if (hasOther) {
          list.push('外省')
        }
        if (hasForeign) {
          list.push('外籍')
        }
        this.changeAreaCheckbox(list)
      }
    })
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getList()
    })
  }

  // 重置表单
  reset (status = false) {
    this.setState({
      name: '',
      actions: undefined,
      areaCheckAll: true,
      typeCheckAll: true,
      detailAreaVisible: false,
      areaCheckedList: this.state.areaOptions.slice(),
      typeCheckedList: this.state.typeOptions.slice(),
      onlyNew: '全部',
      professional: undefined,
      causeactionClass: undefined,
      retire: '全部',
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      if (status) {
        this.getList()
      }
    })
  }

  searchHandle () {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getList()
    })
  }

  componentDidUpdate (prev) {
    const { visible } = this.props
    if ((prev.visible !== visible && !visible)) {
      this.reset(true)
    }
  }

  componentDidMount () {
    this.getDictionary()
    this.getBaseData()
  }

  render () {
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      type: 'radio',
      onChange: (v) => this.onSelectChange(v),
      getCheckboxProps: record => {
        return {
          disabled: this.props.disabledIdList.indexOf(record.id) !== -1,
          name: record.name
        }
      }
    }
    const onRow = (record, index) => {
      return {
        onClick: () => {
          const o = this.state.list[index]
          if (this.props.disabledIdList.indexOf(o.id) !== -1) {
            return false
          }
          const { current, pageSize } = this.state.pagination
          const i = (current - 1) * pageSize + index
          this.setState({ selectedRowKeys: [i] }, () => this.onSelectChange([i]))
        }
      }
    }
    const rowClassName = (record, index) => {
      const o = this.state.list[index]
      if (this.props.disabledIdList.indexOf(o.id) !== -1) {
        return style.disabled
      }
    }
    return (
      <div>
        <div className={style['search-line']}>
          <Row>
            <Col span={8}>
              <Row>
                <Col flex='100px' className={style.label}>名称：</Col>
                <Col flex='auto'>
                  <Input placeholder='请输入' allowClear value={this.state.name} onChange={e => this.setState({ name: e.target.value })} />
                </Col>
              </Row>
            </Col>
            <Col span={8}>
              <Row>
                <Col flex='100px' className={style.label}>工作状况：</Col>
                <Col flex='auto'>
                  <Select className={style.full} value={this.state.retire} placeholder='请选择' onChange={e => this.setState({ retire: e })}>
                    <Option value='全部'>全部</Option>
                    <Option value={0}>在职</Option>
                    <Option value={1}>非在职</Option>
                  </Select>
                </Col>
              </Row>
            </Col>
            <Col span={8}>
              <Row>
                <Col flex='100px' className={style.label}>聘用时间：</Col>
                <Col flex='auto'>
                  <Select className={style.full} value={this.state.onlyNew} placeholder='请选择' onChange={e => this.setState({ onlyNew: e })}>
                    <Option value='全部'>全部</Option>
                    <Option value='2021年3月之前'>2021年3月之前</Option>
                    <Option value='2021年3月1日'>2021年3月1日</Option>
                    <Option value='2021年6月1日'>2021年6月1日</Option>
                  </Select>
                </Col>
              </Row>
            </Col>
          </Row>
        </div>
        <div className={style['search-line']}>
          <Row>
            <Col span={8}>
              <Row>
                <Col flex='100px' className={style.label}>专业：</Col>
                <Col flex='auto'>
                  <Select className={style.full} showSearch allowClear placeholder='请选择' value={this.state.professional} onChange={e => this.setState({ professional: e })}>
                    {
                      this.state.majors.map(li => <Option key={li} value={li}>{li}</Option>)
                    }
                  </Select>
                </Col>
              </Row>
            </Col>
            {/* <Col span={8}>
              <Row>
                <Col flex='100px' className={style.label}>金融专业：</Col>
                <Col flex='auto'>
                  <Select className={style.full} showSearch allowClear placeholder='请选择' value={this.state.causeactionClass} onChange={e => this.setState({ causeactionClass: e })}>
                    {
                      this.state.causeactionClassList.map(li => <Option key={li} value={li}>{li}</Option>)
                    }
                  </Select>
                </Col>
              </Row>
            </Col> */}
            <Col span={8}>
              <Row>
                <Col flex='100px' className={style.label}>擅长专业：</Col>
                <Col flex='auto'>
                  <TreeSelect treeData={this.state.causeActionTree} placeholder='请选择' className={style.full} showSearch allowClear dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} value={this.state.actions} onChange={d => { this.setState({ actions: d }) }} />
                </Col>
              </Row>
            </Col>
          </Row>
        </div>
        <div className={style['search-line']}>
          <span className={style['search-line-label']}>所在区域：</span>
          <Checkbox
            indeterminate={this.state.areaIndeterminate}
            onChange={e => this.changeAllArea(e)}
            checked={this.state.areaCheckAll}
          >全选
          </Checkbox>
          {this.state.detailAreaVisible ? (
            <>
              <div className={style['detail-area']}>
                <Checkbox.Group
                  options={this.state.detailAreaOptions}
                  value={this.state.areaCheckedList}
                  onChange={v => this.changeAreaCheckbox(v)}
                />
                <Button type='link' onClick={() => this.hideDetailArea()}>收起</Button>
              </div>
            </>
          ) : (
            <>
              <Checkbox.Group
                options={this.state.areaOptions}
                value={this.state.areaCheckedList}
                onChange={v => this.changeAreaCheckbox(v)}
              />
              <Button type='link' onClick={() => this.showDetailArea()}>更多</Button>
            </>
          )}
        </div>
        <div className={style['search-line']}>
          <span className={style['search-line-label']}>职业分类：</span>
          <Checkbox
            indeterminate={this.state.typeIndeterminate}
            onChange={e => this.changeAll('type', e)}
            checked={this.state.typeCheckAll}
          >全选
          </Checkbox>
          <Checkbox.Group
            options={this.state.typeOptions}
            value={this.state.typeCheckedList}
            onChange={v => this.changeCheckbox('type', v)}
          />
        </div>
        <div className={style['search-btn-line']}>
          <Space>
            <Button type='primary' onClick={() => this.searchHandle()}>查询</Button>
            <Button type='primary' ghost onClick={() => this.reset(true)}>重置</Button>
          </Space>
        </div>
        <Table loading={this.state.loading} rowSelection={rowSelection} rowClassName={rowClassName} onRow={onRow} className={style.mt16} size='small' pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} columns={getColumns.call(this)} dataSource={this.state.list} />
      </div>
    )
  }
}

ArbitratorList.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func,
  visible: PropTypes.bool,
  caseDetail: PropTypes.object,
  disabledIdList: PropTypes.array
}
ArbitratorList.defaultProps = {
  value: '',
  onChange: () => {},
  visible: false,
  caseDetail: {},
  disabledIdList: []
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(ArbitratorList)
